﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Threading.Tasks;
using SIE.SCADA.SuperSocket.Rpc;
using System.Net;
using System.IO;
using Newtonsoft.Json;
using SIE.SCADA.Common.Helper;
using SIE.SCADA.Common.Log;

namespace SIE.SCADA.ZemtDemo.Common
{
    public class ApiHelper
    {
        public static Response<T> Post<T>(string methodName, object[] paras,string ip = "127.0.0.1")
        {
            try
            {
                HttpWebRequest wReq = (HttpWebRequest)WebRequest.Create(string.Format("http://{0}:{1}/DataService/webapi/RpcInvoke", ip, "7666"));
                wReq.Method = "Post";
                wReq.ContentType = "application/json";
                wReq.Timeout = 50000;
                var rpcRequest = new RpcRequest() { RpcPara = new RpcPara() { MethodName = methodName, Paras = paras } };

                byte[] data = Encoding.UTF8.GetBytes(JsonHelper.JsonSerialize(rpcRequest));
                wReq.ContentLength = data.Length;
                Stream reqStream = wReq.GetRequestStream();
                reqStream.Write(data, 0, data.Length);
                reqStream.Close();
                string result;
                using (StreamReader sr = new StreamReader(wReq.GetResponse().GetResponseStream()))
                {
                    result = sr.ReadToEnd();
                }
                if (methodName != "Heartbeat") {
                    Logger.Info($"Api Post:{methodName},ip:{ip}");
                }
                
                return JsonHelper.JsonDeserialize<Response<T>>(result);
            }
            catch (Exception ex)
            {
                Logger.Warn(ex.Message);
                Logger.Warn(ex.StackTrace);
            }
            return new Response<T>();
            //if (string.IsNullOrEmpty(_server.ECTConfig.IP) || string.IsNullOrEmpty(_server.ECTConfig.ServerIP)) return null;
           
        }
    }
}
